import TokenCheck from './token-check';

const TOKEN_KEY = 'shangcheng-token-asaqw';
const STORAGE_KEY = 'shangcheng-storage-adiuej';

let token = '';

let storage = {};

class LocalStorage {
  constructor() {

  }

  static setObject(k, v) {
    storage[k] = v;
    localStorage.setItem(STORAGE_KEY, JSON.stringify(storage));
  }

  static getObject(k) {
    try {
      storage[k] = storage[k] || JSON.parse(localStorage.getItem(STORAGE_KEY))[k];
      return storage[k];
    } catch (e) {
      return '';
    }

  }

  static delObject(k) {
    delete storage[k];
    localStorage.setItem(STORAGE_KEY, JSON.stringify(storage));
  }

  static getObjectOnce(k) {
    const o = LocalStorage.getObject(k);
    LocalStorage.delObject(k);
    return o;
  }

  static setToken(v) {
    token = v;
    localStorage.setItem(TOKEN_KEY, v);

    LocalStorage.setObject('token-expired-at', Number(new Date()) + 12 * 3600 * 1000);
  }

  static getToken() {
    const expiredAt = LocalStorage.getObject('token-expired-at');
    token = token || localStorage.getItem(TOKEN_KEY);

    if (Number(expiredAt) < Number(new Date()) || !token) {
      TokenCheck.jumpToLoginPage();
    }

    return token;
  }

}

export default LocalStorage;
